<template>
  <el-card class="company-page">
    <div class="header">
      <div class="search">
        <el-form
          :model="formInline"
          class="demo-form-inline"
          label-width="70px"
          label-position="right"
        >
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="标签名称">
                <el-input
                  v-model="formInline.tags"
                  placeholder="请输入"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="城市">
                <el-select
                  v-model="formInline.province"
                  placeholder="请选择"
                  @change="changeSearch"
                >
                  <el-option
                    v-for="item in provincesOption"
                    :key="item"
                    :label="item"
                    :value="item"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="地区">
                <el-select v-model="formInline.city" placeholder="请选择">
                  <el-option
                    v-for="item in areaOption"
                    :key="item"
                    :label="item"
                    :value="item"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="企业简称">
                <el-input
                  v-model="formInline.shortName"
                  placeholder="根据用户名搜索"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="状态">
                <el-select v-model="formInline.status" placeholder="请选择">
                  <el-option
                    v-for="item in statusOption"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <div style="margin-left: 30px">
                <el-button @click="clear">清空</el-button>
                <el-button type="primary" @click="onSubmit">搜索</el-button>
              </div>
            </el-col>
            <el-col
              :span="6"
              :offset="6"
              style="display: flex; justify-content: flex-end"
            >
              <el-button type="success" class="el-icon-edit" @click="add"
                >新增用户</el-button
              >
            </el-col>
          </el-row>
        </el-form>
      </div>
    </div>
    <el-alert
      :title="`共${counts}条记录`"
      type="info"
      show-icon
      :closable="false"
    >
    </el-alert>
    <el-table
      :header-cell-style="{ background: '#FAFAFA' }"
      :data="companyData"
      style="width: 100%; margin-top: 20px"
    >
      <el-table-column prop="id" label="序号" width="80"> </el-table-column>
      <el-table-column prop="number" label="企业编号" width="180">
      </el-table-column>
      <el-table-column prop="shortName" label="企业简称"> </el-table-column>
      <el-table-column prop="tags" label="标签"> </el-table-column>
      <el-table-column prop="username" label="创建者"> </el-table-column>
      <el-table-column prop="addDate" label="创建日期" :formatter="dateFormat">
      </el-table-column>
      <el-table-column prop="remarks" label="备注"> </el-table-column>
      <el-table-column
        prop="state"
        label="状态"
        :formatter="stateFormat"
        width="50"
      >
      </el-table-column>

      <el-table-column label="操作" align="center" width="150">
        <template #default="scope">
          <!-- 编辑按钮 -->
          <el-button
            plain
            type="primary"
            icon="el-icon-edit"
            circle
            @click="edit(scope.row)"
          ></el-button>
          <!-- 是否禁用按钮 -->
          <el-tooltip
            class="item"
            effect="dark"
            :content="scope.row.state === 1 ? '禁用' : '启用'"
            placement="top-start"
          >
            <el-button
              @click="changeState(scope.row)"
              plain
              :type="scope.row.state === 1 ? 'warning' : 'success'"
              :icon="scope.row.state === 1 ? 'el-icon-close' : 'el-icon-check'"
              circle
            ></el-button>
          </el-tooltip>
          <!-- 删除按钮 -->
          <el-button
            plain
            type="danger"
            icon="el-icon-delete"
            circle
            @click="del(scope.row.id)"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination
        background
        layout="prev, pager, next,sizes,jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="params.page"
        :page-sizes="[10, 20, 30, 50]"
        :total="counts"
      >
      </el-pagination>
    </div>
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      width="37%"
      :close-on-click-modal="false"
    >
      <el-form
        :model="companyForm"
        label-width="120px"
        ref="formRef"
        :rules="rules"
      >
        <el-form-item label="企业名称" prop="shortName">
          <el-input v-model="companyForm.shortName"></el-input>
        </el-form-item>
        <el-form-item label="所属公司" prop="company">
          <el-input v-model="companyForm.company"></el-input>
          https://www.tianyancha.com （在此可查询所属公司全称及简称）
        </el-form-item>

        <el-form-item label="城市地区" prop="province">
          <el-row>
            <el-col :span="12">
              <el-select
                v-model="companyForm.province"
                placeholder="请选择"
                @change="changeForm"
              >
                <el-option
                  v-for="item in provincesOption"
                  :key="item"
                  :label="item"
                  :value="item"
                >
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="12">
              <el-select v-model="companyForm.city" placeholder="请选择">
                <el-option
                  v-for="item in areaOption"
                  :key="item"
                  :label="item"
                  :value="item"
                >
                </el-option>
              </el-select>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="方向(企业标签)" prop="tags">
          <el-input v-model="companyForm.tags"></el-input>
        </el-form-item>

        <el-form-item label="备注" prop="remarks">
          <el-input
            style="width: 97%"
            type="textarea"
            v-model="companyForm.remarks"
          ></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </span>
    </el-dialog>
  </el-card>
</template>

<script>
import { companyList, add, disabled, update, remove } from '@/api/hmmm/companys'
import { provinces, citys } from '@/api/hmmm/citys'
import { status } from '@/api/hmmm/constants'

export default {
  data () {
    return {
      formInline: {
        tags: '',
        province: '',
        city: '',
        shortName: '',
        state: null
      },
      params: {
        page: 1,
        pagesize: 10,
        tags: '',
        province: '',
        city: '',
        shortName: '',
        state: null
      },
      title: '',
      dialogVisible: false,

      companyForm: {
        shortName: '',
        company: '',
        province: '',
        city: '',
        tags: '',
        remarks: '',
        isFamous: true
      },
      rules: {
        shortName: [
          { required: true, message: '企业简称不能为空', trigger: 'blur' }
        ],
        company: [
          { required: true, message: '所属公司不能为空', trigger: 'blur' }
        ],
        province: [{ required: true, message: '请选择省份', trigger: 'change' }],
        tags: [{ required: true, message: '请输入标签', trigger: 'blur' }],
        remarks: [{ required: true, message: '备注不能为空', trigger: 'blur' }]
      },

      companyData: [],
      counts: null,

      provincesOption: [],
      areaOption: [],
      statusOption: []
    }
  },
  created () {
    this.companyList()
    this.provinces()
    this.status()
  },
  methods: {
    clear () {
      this.formInline = {}
      this.areaOption = []
    },
    onSubmit () {
      this.params = this.formInline

      this.companyList()
    },
    async companyList () {
      const { data } = await companyList(this.params)

      this.companyData = data.items
      this.counts = data.counts
    },
    dateFormat (row) {
      return this.$dayjs(row.addDate).format('YYYY-MM-DD')
    },
    stateFormat (row) {
      if (row.state === 0) {
        return '禁用'
      } else if (row.state === 1) {
        return '启用'
      }
    },

    async provinces () {
      const res = await provinces()

      this.provincesOption = res
    },
    async changeSearch () {
      const res = await citys(this.formInline.province)
      this.areaOption = res
      this.formInline.city = this.areaOption[0]
    },
    async changeForm () {
      const res = await citys(this.companyForm.province)
      this.areaOption = res
      this.companyForm.city = this.areaOption[0]
    },
    async status () {
      const res = await status
      this.statusOption = res
    },

    handleSizeChange (val) {
      this.params.pagesize = val
      this.companyList()
    },
    handleCurrentChange (current) {
      this.params.page = current
      this.companyList()
    },
    add () {
      this.dialogVisible = true

      this.title = '创建用户'
    },
    edit (row) {
      this.companyForm = { ...row }

      this.dialogVisible = true
      this.title = '编辑用户'
    },
    async save () {
      try {
        if (this.title === '创建用户') {
          await this.$refs.formRef.validate()

          const res = await add(this.companyForm)

          if (res.status === 200) {
            this.$message.success('添加成功')
          } else {
            this.$message.error('添加失败')
          }
        } else {
          this.companyForm.isFamous = Boolean(this.companyForm.isFamous)
          const res = await update(this.companyForm)
          if (res.status === 200) {
            this.$message.success('修改成功')
          } else {
            this.$message.error('修改失败')
          }
        }
        this.dialogVisible = false
        this.companyList()
      } catch (err) {
        console.dir(err, 'err')
      }
    },
    async changeState (row) {
      const confirmResult = await this.$confirm(
        `已成功${row.state === 1 ? '禁用' : '启用'}, 是否继续?`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((err) => err)

      if (confirmResult !== 'confirm') {
        return this.$message.info('您取消了操作')
      }
      try {
        await disabled({
          id: row.id,
          state: row.state === 1 ? 0 : 1
        })
        row.state = row.state === 1 ? 0 : 1
        this.$message.success(`已成功${row.state === 1 ? '禁用' : '启用'}`)
      } catch (error) {
        this.$message('设置状态失败!')
      }
    },

    async del (id) {
      await this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      await remove(id)
      this.$message({
        type: 'success',
        message: '删除成功!'
      })
      this.companyList()
    }
  }
}
</script>

<style scoped lang="scss">
.company-page {
  margin: 20px 20px;

  .pagination {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
  }
  .el-dialog {
    .el-form {
      .el-input {
        width: 97%;
      }
      .el-select {
        margin-right: 10px;
      }
    }
    .dialog-footer {
      display: block;
      text-align: center;
    }
  }
}
</style>
